package com.lxujia.ruankao.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.lxujia.ruankao.model.DbInitModel;
import com.lxujia.ruankao.util.LogUtil;
import com.lxujia.ruankao.util.DatabaseInitUtil;

import org.litepal.LitePal;
import org.litepal.tablemanager.callback.DatabaseListener;

public class DbInitService extends Service {
    private final static String TAG = "DbInitService";
    private boolean mIsInitDb = false;

    public DbInitService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        LitePal.registerDatabaseListener(new DatabaseListener() {
            @Override
            public void onCreate() {
                // fill some initial data
                LogUtil.d(TAG, "LitePad DB oncreate");
                initDb();
            }

            @Override
            public void onUpgrade(int oldVersion, int newVersion) {
                LogUtil.d(TAG, "LitePad DB onUpgrade");
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // 不进行数据库操作，默认不会开始创建数据库，调用此句后就会开始创建数据库了
        //SQLiteDatabase db = LitePal.getDatabase();
        //db.close();
        DbInitModel dbInitModel = LitePal.where("initSuccess == 1").findFirst(DbInitModel.class);
        LogUtil.d(TAG, "start dbInitModel = " + dbInitModel);
        if (dbInitModel == null || dbInitModel.getInitSuccess() != 1) {
            // 数据库未初始化完成
            LogUtil.d(TAG, "start init db");
            initDb();
        } else {
            updateDb();
        }

        return Service.START_NOT_STICKY;
    }

    private void initDb() {
        if (mIsInitDb) {
            return;
        }
        mIsInitDb = true;

        LogUtil.d(TAG, "initDbData start");

        new DatabaseInitUtil(getApplicationContext()).initDbData();
    }

    private void updateDb() {
        if (mIsInitDb) {
            return;
        }
        mIsInitDb = true;

        LogUtil.d(TAG, "updateDb start");

        new DatabaseInitUtil(getApplicationContext()).updateDbData();
    }
}